import {
  getArticleListActionCreator,
  refreshArticleListActionCreate,
} from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
// import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'

type ListPopsType = {
  channelId: number
}

const ArticleList = ({ channelId }: ListPopsType) => {
  const dispatch = useDispatch()
  const history = useHistory()
  // 一进入文章列表组件, 拿着channelId 获取对应频道下的文章列表数据
  // 下面的滚动组件 会自动发送一次(会和下面的冲突)
  // useEffect(() => {
  //   dispatch(getArticleListActionCreator(channelId, Date.now().toString()))
  // }, [dispatch, channelId])

  const channelActicles = useSelector(
    (state: RootState) => state.home.channelArticles
  )

  // timestamp 就是上次的请求结果中的pre_timestamp, 刚好用于请求更早的数据!!!
  // 如果没有数据了, pre_timestamp就是null
  const { articles = [], timestamp } = channelActicles[channelId] || {}
  // console.log('为什么会变成对象', articles)

  return (
    <div className={styles.root}>
      {/* 下拉刷新 */}
      <PullToRefresh
        onRefresh={async () => {
          await dispatch(
            refreshArticleListActionCreate(channelId, Date.now().toString())
          )
        }}
      >
        {/* 文章列表中的每一项 */}
        {articles.map((item, index) => (
          <div
            className="article-item"
            key={item.art_id}
            onClick={() => {
              history.push(`/article/${item.art_id}`)
            }}
          >
            <ArticleItem type={item.cover.type} article={item} />
          </div>
        ))}

        {/* 无限滚动 */}
        {/* hasMore 这个表示触底后是否调用loadMore函数 */}
        {/* loadMore 记在更多数据的一个函数 */}
        <InfiniteScroll
          threshold={50}
          hasMore={!timestamp !== null}
          loadMore={async () => {
            await dispatch(
              getArticleListActionCreator(
                channelId,
                timestamp || Date.now().toString()
              )
            )
          }}
        ></InfiniteScroll>
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
